<template>
  <div class="content-wrap">
    <!-- 操作框 -->
    <operate-area
      ref="operateArea"
      :btn-auth="{enable:false,disable:false}"
      :btn-text="{add:'添加',del:'删除'}"
      :placeholder-text="'名称'"
      :search-value.sync="searchVal"
      @addUser="addRole"
      @deleteUser="delRole"
      @queryData="getDataList"
    ></operate-area>
    <!-- table -->
    <el-table
      v-loading="tLoading"
      :data="tableData"
      @row-click="checkDetail"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="60"></el-table-column>
      <el-table-column :show-overflow-tooltip="true" label="#" type="index" width="60">
        <template slot-scope="scope">
          <span>{{ scope.$index+(pageNo - 1) * pageSize + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="名称" min-width="180" prop="roleName" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column label="描述" min-width="240" prop="description" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column label="Unicode" min-width="120" prop="code" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column
        :filter-method="filterTag"
        :filters="[{ text: '启用', value: '1' }, { text: '禁用', value: '0' }]"
        filter-placement="bottom-end"
        label="状态"
        prop="status"
        width="96"
      >
        <template slot="header" slot-scope="{ column }">
          <span>{{ column.label }}</span>
          <i class="iconfont iconicon_filtrate fs13"></i>
        </template>
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.status === '1' ? 'success' : 'info'"
            disable-transitions
          >{{ scope.row.status === '1' ? '启用' : '禁用' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="60">
        <template slot-scope="scope">
          <el-tooltip content="另存" placement="top">
            <i class="iconfont iconicon_save fs16 pointer" @click.stop="copySave(scope.row.id)"></i>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!--分页组件-->
    <pagination :page.sync="pageNo" :total="total" @pagination="getDataList" />

    <!-- 新增/另存 角色 -->
    <drawer
      :before-close="handleClose"
      :close-on-press-escape="false"
      :direction="'rtl'"
      :title="currentStatus[cutOperate]"
      :visible="dialogVisible"
      class="add-user-drawer"
      custom-class="demo-drawer"
      size="368px"
      @close="closeDrawer"
    >
      <div class="demo-drawer__content">
        <role-info ref="addRole" :current-data="formInfo" :is-edit="false"></role-info>
        <footer-btn @cancel="cancel" @submitSave="submitSave"></footer-btn>
      </div>
    </drawer>

    <!-- 角色 详情 -->
    <drawer
      :before-close="handleCloseDetail"
      :close-on-press-escape="false"
      :visible.sync="dialogDetail"
      direction="rtl"
      size="416px"
      title="编辑角色"
    >
      <div class="demo-drawer__content">
        <el-tabs class="user-detail-tabs-wrap" tab-position="left" type="border-card" value="edit" @tab-click="tabChange">
          <!-- 编辑 -->
          <el-tab-pane name="edit">
            <span slot="label">
              <i class="iconfont iconicon_detail"></i>
            </span>

            <div class="detail-title flex-space-between">
              <p class="title fs16">详细信息</p>
              <el-button v-if="isEdit" round type="primary" @click="editRole">
                <i class="iconfont iconicon_edit"></i>
                编辑
              </el-button>
            </div>
            <role-info
              ref="editRole"
              :class="isEdit ? '' : 'editshow'"
              :current-data="formInfo"
              :is-edit="isEdit"
            ></role-info>

            <footer-btn
              ref="editFooter"
              :class="isEdit ? '' : 'footerbtnshow'"
              @cancel="cancelEdit"
              @submitSave="saveEdit"
            ></footer-btn>
          </el-tab-pane>

          <el-tab-pane name="user">
            <span slot="label">
              <i class="iconfont iconicon_users"></i>
            </span>
            <div class="detail-title flex-space-between">
              <p class="title fs16">用户信息</p>
              <el-button
                round
                size="mini"
                type="primary"
                @click="addUsers"
              >
                <i class="iconfont iconicon_add"></i>
                新增
              </el-button>
            </div>
            <div class="user-info-wrap">
              <el-table v-loading="wsloading" :data="users">
                <el-table-column
                  label="登录名ID"
                  min-width="60"
                  prop="loginName"
                  :show-overflow-tooltip="true"
                ></el-table-column>
                <el-table-column
                  label="姓名"
                  min-width="60"
                  prop="userName"
                  :show-overflow-tooltip="true"
                ></el-table-column>
                <el-table-column label="操作" width="60">
                  <template slot-scope="scope">
                    <popover
                      :visible-pop.sync="visiblePop1"
                      @submit="delUserSubmit(scope.row)"
                    >
                      <i class="iconfont iconicon_trash fs13 cursor-pointer"></i>
                    </popover>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </drawer>
    <el-dialog
      :modal="false"
      :modal-append-to-body="false"
      :visible.sync="addUserDrawer"
      class="dialog-wrap userdialog"
      title="新增用户"
      width="400px"
    >
      <el-form ref="form" label-width="60px">
        <el-form-item label="用户" style="margin: 0;">
          <el-select v-model="userIds" filterable multiple placeholder="请选择用户">
            <el-option
              v-for="item in selectUser"
              :key="item.id"
              :label="item.userName"
              :value="item.id"
            >
              <span style="float: left">{{ item.userName }}</span>
              <span style="float: left">({{ item.loginName }})</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <operate-btn @cancel="cancelClearUser" @submitSave="saveUser"></operate-btn>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { queryAllList, queryAllGroupList } from '@/api/adminPage/userManage/user'
import operateBtn from '@/components/CancelAndSubmitBtnGroup'
import Popover from '@/components/Popover/index'
import OperateArea from '@/components/OperateArea/index'
import Drawer from '@/components/Drawer/index'
import Pagination from '@/components/Pagination/index'
import FooterBtn from './footerBtn.vue'
import RoleInfo from './roleInfo.vue'
import {
  queryList,
  add,
  copyAdd,
  view,
  update,
  del
} from '@/api/adminPage/userManage/role'

export default {
  name: 'User',
  components: {
    operateBtn,
    OperateArea,
    Pagination,
    Drawer,
    FooterBtn,
    RoleInfo,
    Popover
  },
  data() {
    return {
      addUserGroupDrawer: false,
      selectUserGroups: [],
      userGroupIds: [],
      selectUser: [],
      addUserDrawer: false,
      userIds: [],
      wsloading: false,
      visiblePop: false,
      visiblePop1: false,
      currentId: '',
      tableData: [],
      searchVal: '',
      pageNo: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      formInfo: {
        roleName: '',
        description: '',
        code: '',
        status: '0', // 0-未启用   1-是启用
        userIds: [],
        userGroupIds: []
      },
      multipleSelection: [],
      cutOperate: 0, // 0-新增 1-另存
      dialogDetail: false,
      isEdit: true,
      tLoading: false,
      tabName: 'edit',
      users: [],
      userGroups: []
    }
  },
  computed: {
    records() {
      return this.multipleSelection.length
    },
    currentStatus() {
      return ['新增角色', '另存角色']
    }
  },
  created() {
    this.getDataList()
  },
  methods: {
    saveUser() {
      this.formInfo.userIds = this.userIds
      update(this.formInfo).then(res => {
        this.addUserDrawer = false
        this.$message({
          type: 'success',
          message: '添加成功'
        },
        view(this.currentId).then(res => {
          this.wsloading = false
          this.users = res.result.users
        })
        )
      })
    },
    cancelClearUser() {
      this.userIds = []
      this.addUserDrawer = false
    },
    addUsers() {
      this.userIds = []
      this.addUserDrawer = true
      queryAllList().then(res => {
        this.selectUser = res.result
      })
    },
    delUserSubmit(item) {
      this.removeByValue(this.formInfo.userIds, item.id)
      update(this.formInfo).then(res => {
        this.$message({
          type: 'success',
          message: '删除成功'
        },
        view(this.currentId).then(res => {
          this.wsloading = false
          this.users = res.result.users
        })
        )
      })
    },
    removeByValue(arr, val) {
      for (var i = 0; i < arr.length; i++) {
        if (arr[i] === val) {
          arr.splice(i, 1)
          break
        }
      }
    },
    tabChange(params) {
      this.tabName = params.name
      switch (params.name) {
        case 'user':
          this.wsloading = true
          view(this.currentId).then(res => {
            this.wsloading = false
            this.users = res.result.users
          })
          break
        case 'usergroup':
          this.wsloading = true
          view(this.currentId).then(res => {
            this.wsloading = false
            this.userGroups = res.result.userGroups
          })
          break
      }
    },
    closeDrawer() {
      if (this.$refs.addRole.$refs.addInfo) {
        // 延时执行
        this.$nextTick(function() {
          console.log(222)
          this.$refs.addRole.$refs.addInfo.clearValidate()
        })
      }
    },
    getDataList(value) {
      if (value && typeof value === 'object') {
        this.pageNo = value.page
        this.pageSize = value.limit
      }
      const params = {
        pageNo: this.pageNo > 0 ? this.pageNo : 1,
        pageSize: this.pageSize,
        t: {
          roleName: this.searchVal
        }
      }
      this.tLoading = true
      queryList(params).then(res => {
        this.tLoading = false
        const records = res.result.records
        this.tableData = records
        this.total = res.result.total
      })
    },
    filterTag(value, row, column) {
      const property = column['property']
      return row[property] === value
    },
    addRole() {
      this.formInfo = {
        roleName: '',
        description: '',
        code: '',
        status: '1',
        userIds: [],
        userGroupIds: []
      }
      this.cutOperate = 0
      this.dialogVisible = true
    },
    submitSave() {
      this.$refs.addRole.$refs.addInfo.validate(valid => {
        if (valid) {
          if (this.cutOperate === 1) {
            // 另存
            copyAdd(this.formInfo).then(res => {
              this.getDataList()
              this.dialogVisible = false
            })
          } else if (this.cutOperate === 0) {
            // 新增
            add(this.formInfo).then(res => {
              this.getDataList()
              this.dialogVisible = false
            })
          }
        }
      })
    },
    cancel() {
      this.dialogVisible = false
      this.formInfo = {
        roleName: '',
        description: '',
        code: '',
        status: '0', // 0-未启用   1-是启用
        userIds: [],
        userGroupIds: []
      }
    },
    handleClose(done) {
      this.dialogVisible = false
    },
    gerRoleInfo(id) {
      view(id).then(res => {
        const resData = res.result
        this.formInfo = {
          id: id,
          roleName: resData.roleName,
          description: resData.description,
          code: resData.code,
          status: resData.status,
          userIds: resData.userIds,
          userGroupIds: resData.userGroupIds
        }
      })
    },
    copySave(id) {
      this.gerRoleInfo(id)
      this.cutOperate = 1
      this.dialogVisible = true
    },
    delRole() {
      if (this.records === 0) {
        this.$message({ message: '请选择需要删除的角色' })
      } else {
        this.handleDel()
      }
    },
    handleDel() {
      const ids = this.getOperateIds()
      del(ids).then(res => {
        this.$message({ message: '删除成功', type: 'success' })
        this.getDataList()
      })
    },
    handleSelectionChange(val) {
      if (val.length) {
        this.$refs.operateArea.$children[1].selectIndex = 1
      } else {
        this.$refs.operateArea.$children[1].selectIndex = -1
      }
      this.multipleSelection = val
    },
    getOperateIds() {
      const ids = []
      this.multipleSelection.forEach((item, index) => {
        ids.push(item.id)
      })
      return ids
    },
    handleCloseDetail() {
      this.isEdit = true
      this.dialogDetail = false
    },
    cancelEdit() {
      this.isEdit = true
    },
    saveEdit() {
      if (this.isEdit) {
        this.$message({ message: '你未编辑角色信息，无需保存' })
        return
      }
      this.$refs.editFooter.loading = true
      this.$refs.editRole.$refs.addInfo.validate(valid => {
        if (valid) {
          update(this.formInfo).then(res => {
            this.isEdit = true
            this.dialogDetail = false
            this.getDataList()
            this.$message({ message: '保存成功', type: 'success' })
          })
        }
        this.$refs.editFooter.loading = false
      })
    },
    checkDetail(item) {
      this.currentId = item.id
      this.gerRoleInfo(item.id)
      this.dialogDetail = true
    },
    editRole() {
      this.isEdit = false
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
@import "~@/assets/styles/variables";
@import "~@/assets/styles/user-drawer.scss";

::v-deep .el-table tbody tr:hover > td {
  cursor: pointer;
}
::v-deep .user-detail-tabs-wrap {
  height: calc(100vh - 67px);
  border: none;
  .detail-title {
    margin-bottom: 25px;
    color: $fontColor;
  }
  .el-tabs__header {
    margin-right: 0;
    background: $background;
  }
  .el-tabs__item {
    padding: 0 13px;
    height: 59px;
    line-height: 59px;
  }
  .el-tabs__content {
    padding: 16px;
  }
  .user-detail-scroll {
    padding-bottom: 68px;
    height: calc(100vh - 68px);
    ::v-deep .el-scrollbar__wrap {
      overflow-x: hidden;
    }
  }
}
</style>
